package spider

import (
	"context"
	"encoding/json"
	"fmt"
	"gdei_healthy_colly/log"
	"github.com/spf13/cast"
	"go.uber.org/zap"
	"io/ioutil"
	"net/http"
	"net/url"
	"strings"
)

// 登陆请求构造器
func loginRequest(ctx context.Context, username, password string, rememberMe bool) (req *http.Request, err error) {
	req, err = http.NewRequestWithContext(ctx, opMapper[opLogin].Method, opMapper[opLogin].Url(), strings.NewReader(url.Values{
		"username":   {username},
		"password":   {password},
		"rememberMe": {cast.ToString(rememberMe)},
	}.Encode()))
	if err != nil {
		return
	}
	req.Header.Set("Content-Type", "application/x-www-form-urlencoded")
	req.Header.Set("User-Agent", UserAgent)
	return req, nil
}

// 发送登陆请求
func login(ctx context.Context, ac Account) (err error) {
	log.Logger.Info("[登陆]",
		zap.String("ID", ac.GetId()),
		zap.String("Username", ac.GetUsername()),
	)
	if ac == nil {
		return fmt.Errorf("空指针")
	}

	loginReq, err := loginRequest(ctx, ac.GetUsername(), ac.GetPassword(), ac.GetRemember())
	if err != nil {
		return
	}

	resp, err := ac.GetClient().Do(loginReq)
	if err != nil {
		return
	}
	defer resp.Body.Close()

	if resp.StatusCode != http.StatusOK {
		return fmt.Errorf("[登陆失败]状态码: %d", resp.StatusCode)
	}

	// 读取一下数据
	r := new(respStruct)
	respData, err := ioutil.ReadAll(resp.Body)
	if err != nil {
		return
	}

	if err = json.Unmarshal(respData, r); err != nil {
		return
	}
	if r.Code != 0 {
		return fmt.Errorf("[登陆失败]响应内容: %v", *r)
	}

	return
}
